package com.bw.common.utils

import com.bw.common.BaseApplication
import com.bw.common.common.ConstantValue
import com.bw.common.commonentity.UserEntity
import com.bw.common.encry.AESUtils
import com.google.gson.Gson
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi

/**
 * @author:created by hahajing
 * 时间：2024/5/7 0007
 * 企鹅号:444511958
 * 描述:
 */
object UserUtils {
    //当前登录的用户
    private var user:String by SharedPreferenceDelegate<String>(
        BaseApplication.getApplicationContext(),
        ConstantValue.SP_NAME,
        ConstantValue.SP_KEY_USER,"")

    /**
     * 保存用户信息（json）存储到sp
     */
    fun saveUser(userinfo:String){
        val cryptStr = AESUtils.getInstance().encrypt(userinfo,ConstantValue.AESKEY)
        user=cryptStr
    }

    /**
     * 从sp获取登录用户对象
     */
    fun getCurrentUser():UserEntity?{
        if (user.isBlank()){
            return null
        }
        val decryptStr = AESUtils.getInstance().decrypt(user,ConstantValue.AESKEY)
        val userEntity = Gson().fromJson<UserEntity>(decryptStr,UserEntity::class.java)
        return userEntity
    }

    @OptIn(ExperimentalEncodingApi::class)
    fun getCurrentUserStr():String{
        if (user.isBlank()){
            return ""
        }
        val decryptStr = AESUtils.getInstance().decrypt(user,ConstantValue.AESKEY)
        //base64编码处理json逗号问题
        val base64Str = Base64.encode(decryptStr.toByteArray())
        return base64Str
    }

    @OptIn(ExperimentalEncodingApi::class)
    fun getUserFromStr(str:String):UserEntity{
        val base64Str = String(Base64.decode(str.toByteArray()))
        return Gson().fromJson(base64Str,UserEntity::class.java)
    }
}